import {
  CozeAPI,
  ChatEventType,
  ChatStatus,
  COZE_CN_BASE_URL,
  RoleType,
} from '@coze/api';

const token =
  process.env.COZE_API_TOKEN ||
  'pat_tp1echj4I6l1aDEyjdgkdaRLVh6BeX8QmDayHW28U98YU6oLrS3IHNHbLc4mAmmH';
const botId = process.env.COZE_BOT_ID || '7448900659833470976';
const baseURL = COZE_CN_BASE_URL;

const client = new CozeAPI({
  baseURL,
  token,
  allowPersonalAccessTokenInBrowser: true,
});

const sendToAi = async (content) => {
  const stream = await client.chat.stream({
    bot_id: botId,
    additional_messages: [
      {
        role: RoleType.User,
        content: content,
        content_type: 'text',
      },
    ],
  });

  return new Promise(async (resolve, reject) => {
    let context = '';
    for await (const part of stream) {
      if (part.event === ChatEventType.CONVERSATION_MESSAGE_DELTA) {
        // process.stdout.write(part.data.content);
        context = context + part.data.content;
      }
      // if (part.event === ChatEventType.CONVERSATION_MESSAGE_COMPLETED) {
      //   console.log(part.data.content);
      // }
      if (part.event === ChatEventType.DONE) {
        return resolve({
          data: context,
        });
      }
      // if (part.event === ChatEventType.ERROR) {
      //   reject({
      //     code: -1,
      //     data: 'err',
      //   });
      // }
    }
  });
};

export { sendToAi };
